import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Paint;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Stack;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.Document;

import org.apache.commons.collections15.Transformer;

import com.jidesoft.swing.JideSplitPane;

import edu.uci.ics.jung.visualization.VisualizationViewer;
import javax.swing.border.LineBorder;
import java.awt.FlowLayout;
import java.awt.Component;
import com.jidesoft.swing.JideSplitPaneLayout;
import java.awt.ComponentOrientation;

public class GUI extends JFrame {
	String[] end_cities = { "none" };
	String[] start_cities = { "none" };
	String[] heuristics = { "Straight Line", "Fewest Links" };

	// Conn and loc variables
	JMenuItem mntmLoadConnectionAnd;

	JFrame location;
	JTextField connfile;
	JTextField locfile;
	JButton find1;
	JButton find2;

	private JPanel contentPane;
	private JPanel pane;
	private JButton ok;
	private JButton cncl;
	Scanner scanner;
	Document doc;
	protected File fl1;
	protected File fl2;
	protected String line;
	private JLabel lblExcludedCities;
	private JCheckBox chckbxNon;
	private JComboBox comboBox_start_city;
	private JComboBox comboBox_end_city;
	private JPanel heuristic_pane;
	private JLabel lblHeuristic;
	private JLabel lblStartCity;
	private JLabel lblEndCity;
	private JComboBox comboBox_heruristic;
	private JPanel chckPane;
	private GridLayout layoutbox;
	private JPanel excludedcitiespane;
	private BoxLayout ly;
	private JButton exe;
	ArrayList<Node> nodes;
	Astar astar;
	private JPanel Graph_pane;
	private JButton loadGraph;
	protected VisualizationViewer<Node, Edge> viserver=null;
	Path pathtotarget;
	private Stack<Node> finalstack;
	protected int counter;
	private JButton step;
	protected Node source;
	protected Node target;
	protected String starnode;
	protected String endnode;
	protected Thread threadPath=null;
	private Object lock1 = new Object();
	private JideSplitPane splitPanelGrapth;
	private JTextArea textPane;
	private JScrollPane ScrolltextPane;
	private JSplitPane splitPanelLabel;
	private JPanel PanelLabel;
	private JTextArea ColorStartCity;
	private JSplitPane splitPane;
	private JideSplitPane ExcludedCitiesSplitPanel;
	private JideSplitPane HeuristicsplitPane;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					// select Look and Feel
					//		            UIManager.setLookAndFeel("com.jtattoo.plaf.texture.TextureLookAndFeel");
					UIManager.setLookAndFeel("com.jtattoo.plaf.noire.NoireLookAndFeel");
					//					UIManager.setLookAndFeel("com.jtattoo.plaf.aero.AeroLookAndFeel");

					GUI frame = new GUI();
					frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
					frame.setVisible(true);
					frame.restoreDefaults();
					//					frame.setVisible(true);			
					
					//					frame.setResizable(false);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */

	private void restoreDefaults() {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				HeuristicsplitPane.setDividerLocation(0,0);
//				splitPanelGrapth.setDividerLocation(0, location)
			}
		});
	}

	public GUI() {
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));
		setBounds(200, 200, 1088, 612);

		setTitle("A* algorithm");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//		setBounds(100, 100, 587, 412);

		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		JMenu mnMenu = new JMenu("Menu");
		menuBar.add(mnMenu);

		JMenuItem mntmExit = new JMenuItem("Exit");
		mntmExit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				System.exit(DISPOSE_ON_CLOSE);
			}
		});
		mnMenu.add(mntmExit);

		mntmLoadConnectionAnd = new JMenuItem(
				"Load Connection and Location File");
		mntmLoadConnectionAnd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {

				loadingpanel();

			}
		});
		mnMenu.add(mntmLoadConnectionAnd);

		splitPane = new JSplitPane();
		contentPane.add(splitPane, BorderLayout.CENTER);
		
		HeuristicsplitPane = new JideSplitPane();
		HeuristicsplitPane.setInitiallyEven(false);
		HeuristicsplitPane.setDragResizable(false);
		HeuristicsplitPane.setOrientation(JideSplitPane.VERTICAL_SPLIT);
		HeuristicsplitPane.setDividerLocation(0,0);

		ExcludedCitiesSplitPanel = new JideSplitPane();
		ExcludedCitiesSplitPanel.setOrientation(JSplitPane.VERTICAL_SPLIT);
		ExcludedCitiesSplitPanel.setDragResizable(false);
		
		
		lblExcludedCities = new JLabel("Excluded Cities");
		excludedcitiespane = new JPanel();
		excludedcitiespane.setMaximumSize(new Dimension(32767, 8));
		excludedcitiespane.setBorder(new LineBorder(new Color(0, 0, 0)));
		excludedcitiespane.setPreferredSize(new Dimension(0, 5));
		
		chckPane = new JPanel();
		layoutbox = new GridLayout(5, 5);
		chckPane.setLayout(layoutbox);
		ly = new BoxLayout(excludedcitiespane, BoxLayout.X_AXIS);
		excludedcitiespane.setLayout(ly);
		excludedcitiespane.add(Box.createHorizontalGlue());
		excludedcitiespane.add(lblExcludedCities);
		excludedcitiespane.add(Box.createHorizontalGlue());

		ExcludedCitiesSplitPanel.add(excludedcitiespane);
		ExcludedCitiesSplitPanel.add(chckPane);

		

		heuristic_pane = new JPanel();
//		heuristic_pane.setPreferredSize(new Dimension(10, 80));
		heuristic_pane.setMaximumSize(new Dimension(32767, 80));


		HeuristicsplitPane.add(heuristic_pane);			
		HeuristicsplitPane.add(ExcludedCitiesSplitPanel);

		splitPane.setLeftComponent(HeuristicsplitPane);

		
		
		lblHeuristic = new JLabel("Heuristic");
		comboBox_heruristic = new JComboBox(heuristics);


		lblStartCity = new JLabel("Start City");
		comboBox_start_city = new JComboBox(start_cities);		
		comboBox_start_city.addItemListener(new ItemListener() {

			@Override
			public void itemStateChanged(ItemEvent e) {
				if (viserver!=null){

					Transformer<Node,Paint> vertexColor = new Transformer<Node,Paint>() {
						@Override
						public Paint transform(Node arg0) {

							String starnode = (String)comboBox_start_city.getSelectedItem();
							String endnode = (String)comboBox_end_city.getSelectedItem();
							if (starnode.equals("none")){
								return Color.WHITE;
							}
							if (endnode.equals("none")){
								return Color.WHITE;
							}
							Node source = findNode(starnode);
							Node target = findNode(endnode);

							if(arg0==source){
								return Color.YELLOW;
							}
							else if(arg0==target){
								return Color.GREEN;
							}
							else {
								return Color.WHITE;
							}

						}
					};
					viserver.getRenderContext().setVertexFillPaintTransformer(vertexColor);
					Graph_pane.updateUI();
				}

			}
		});

		lblEndCity = new JLabel("End City");
		comboBox_end_city = new JComboBox(end_cities);
		comboBox_end_city.addItemListener(new ItemListener() {

			@Override
			public void itemStateChanged(ItemEvent arg0) {
				if (viserver!=null){

					Transformer<Node,Paint> vertexColor = new Transformer<Node,Paint>() {
						@Override
						public Paint transform(Node arg0) {
							String starnode = (String)comboBox_start_city.getSelectedItem();
							String endnode = (String)comboBox_end_city.getSelectedItem();
							if (starnode.equals("none")){
								return Color.WHITE;
							}
							if (endnode.equals("none")){
								return Color.WHITE;
							}
							Node source = findNode(starnode);
							Node target = findNode(endnode);

							if(arg0==source){
								return Color.YELLOW;
							}
							if(arg0==target){
								return Color.GREEN;
							}
							return Color.WHITE;
						}
					};
					//					viserver.getRenderContext().setVertexFillPaintTransformer(resetColor);
					viserver.getRenderContext().setVertexFillPaintTransformer(vertexColor);
					Graph_pane.updateUI();
				}

			}
		});

		
		chckbxNon = new JCheckBox("none");
		chckbxNon.setSelected(true);

		chckPane.add(chckbxNon,BorderLayout.CENTER);

		splitPanelGrapth = new JideSplitPane();
		splitPanelGrapth.setAlignmentX(Component.CENTER_ALIGNMENT);
		JideSplitPaneLayout jideSplitPaneLayout = (JideSplitPaneLayout) splitPanelGrapth.getLayout();
		splitPanelGrapth.setInitiallyEven(false);
		splitPanelGrapth.setOrientation(JSplitPane.HORIZONTAL_SPLIT);


		Graph_pane = new JPanel();
		PanelLabel = new JPanel();
		PanelLabel.setMinimumSize(new Dimension(0, 5));
		PanelLabel.setMaximumSize(new Dimension(10, 10));

		splitPanelLabel = new JSplitPane();
		splitPanelLabel.setOrientation(JSplitPane.VERTICAL_SPLIT);

		splitPanelLabel.setTopComponent(PanelLabel);

		ColorStartCity = new JTextArea();
		ColorStartCity.setBackground(Color.YELLOW);
		ColorStartCity.setColumns(5);

		JTextArea ColorEndCity = new JTextArea();
		ColorEndCity.setEditable(false);
		ColorEndCity.setBackground(Color.GREEN);
		ColorEndCity.setColumns(5);

		JTextArea ColorFinalPath = new JTextArea();
		ColorFinalPath.setColumns(5);
		ColorFinalPath.setBackground(Color.MAGENTA);

		JTextArea ColorPathCalculated = new JTextArea();
		ColorPathCalculated.setColumns(5);
		ColorPathCalculated.setBackground(Color.BLUE);

		JLabel lblStartCity_1 = new JLabel("Start City");

		JLabel lblEndCity_1 = new JLabel("End City");

		JLabel lblFinalPath = new JLabel("Final Path");

		JLabel lblPathCalculated = new JLabel("Path Calculated");
		PanelLabel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		PanelLabel.add(lblStartCity_1);
		PanelLabel.add(ColorStartCity);
		PanelLabel.add(lblEndCity_1);
		PanelLabel.add(ColorEndCity);
		PanelLabel.add(lblFinalPath);
		PanelLabel.add(ColorFinalPath);
		PanelLabel.add(lblPathCalculated);
		PanelLabel.add(ColorPathCalculated);
		splitPanelLabel.setBottomComponent(Graph_pane);


		textPane = new JTextArea();
		textPane.setColumns(6);
		textPane.setEditable(false);

		ScrolltextPane = new JScrollPane(textPane);
		ScrolltextPane.setPreferredSize(new Dimension(30, getContentPane().getHeight()));

		splitPanelGrapth.add(splitPanelLabel);
		splitPanelGrapth.add(ScrolltextPane);

		splitPane.setRightComponent(splitPanelGrapth);


		exe = new JButton("Execute");
		exe.setEnabled(false);
		exe.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// Redirect to Text Pane

				String selecteditem = (String)comboBox_heruristic.getSelectedItem();
				if (selecteditem.equals("Straight Line")){
					Heuristic(1,0);					
				}
				else if (selecteditem.equals("Fewest Links")){
					Heuristic(1,1);
				}		

			}
		});

		loadGraph = new JButton("Load Graph");
		loadGraph.setEnabled(false);
		loadGraph.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				Graph_pane.removeAll();
				Graph graph = new Graph(nodes, Graph_pane);
				viserver = graph.GenGraph();
				final String starnode = (String)comboBox_start_city.getSelectedItem();
				final String endnode = (String)comboBox_end_city.getSelectedItem();
				final Node source = findNode(starnode);
				final Node target = findNode(endnode);

				Transformer<Node,Paint> vertexColor = new Transformer<Node,Paint>() {
					@Override
					public Paint transform(Node arg0) {
						// TODO Auto-generated method stub


						if (starnode.equals("none")){
							return Color.WHITE;
						}
						if (endnode.equals("none")){
							return Color.WHITE;
						}					

						if(arg0==source){
							return Color.YELLOW;
						}
						if(arg0==target){
							return Color.GREEN;
						}
						return Color.WHITE;
					}
				};

				viserver.getRenderContext().setVertexFillPaintTransformer(vertexColor);
				Graph_pane.updateUI();
				step.setEnabled(true);
			}
		});

		step = new JButton("Step");
		step.setEnabled(false);
		step.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {

				String selecteditem = (String)comboBox_heruristic.getSelectedItem();
				if (selecteditem.equals("Straight Line")){
					synchronized (lock1) {					
						lock1.notifyAll();
					}
					Heuristic(0,0);					
				}
				else if (selecteditem.equals("Fewest Links")){
					synchronized (lock1) {					
						lock1.notifyAll();
					}
					Heuristic(0,1);
				}


			}
		});
		layoutPanel();
	}

	private void Heuristic(final int mode, final int H){

		//Select start and end city
		starnode = (String)comboBox_start_city.getSelectedItem();
		endnode = (String)comboBox_end_city.getSelectedItem();

		source = findNode(starnode);
		target = findNode(endnode);

		//Select cities to exclude
		final int count =	chckPane.getComponentCount();
		for (int i=0; i<count;i++){
			JCheckBox ck = (JCheckBox) chckPane.getComponent(i);
			if(ck.isSelected()){
				String nm = ck.getText();
				Node exn= findNode(nm);
				exn.setVisited(true);
			}
		}	

		// A* algorithm object
		Runnable ro = new Runnable() {

			@Override
			public void run() {
				textPane.setText("");
				if(mode==1){
					step.setEnabled(false);
				}
				exe.setEnabled(false);
				loadGraph.setEnabled(false);
				chckPane.setEnabled(false);
				comboBox_heruristic.setEnabled(false);
				comboBox_start_city.setEnabled(false);
				comboBox_end_city.setEnabled(false);
				int count =	chckPane.getComponentCount();
				for (int i=0; i<count;i++){
					JCheckBox ck = (JCheckBox) chckPane.getComponent(i);
					ck.setEnabled(false);
				}


				astar = new Astar(lock1,textPane);
				pathtotarget = null;
				try {
					pathtotarget = astar.calculatePath(source, target,viserver, mode,H);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(pathtotarget.getStack().isEmpty()){
					String temp = textPane.getText();
					textPane.setText("");
					textPane.append("Final Path Info: UNKNOWN\n");
					textPane.append("Cost Function: UNKNOWN\n");					
					textPane.append("***********************\n");
					textPane.append(temp+"\n");	

					Transformer<Node, Paint> vertexColor = new Transformer<Node, Paint>() {
						@Override
						public Paint transform(Node arg0) {
							if (arg0 == source) {
								return Color.YELLOW;
							}
							else if (arg0 == target) {
								return Color.GREEN;
							}									
							else{								
								return Color.WHITE;
							}

						}
					};
					viserver.getRenderContext().setVertexFillPaintTransformer(vertexColor);							
					Graph_pane.updateUI();

				}
				else{
					String temp = textPane.getText();
					textPane.setText("");
					finalstack = pathtotarget.getStack();

					textPane.append("Final Path Info:\n");
					if (H==0){
						textPane.append("Cost Function: "+pathtotarget.getCostFunction()+"\n");
						textPane.append("Straight Line Distance: "+pathtotarget.getHeuristicDistance()+"\n");
						textPane.append("Distance To Source: "+pathtotarget.getSourceDistance()+"\n");
					}
					else if (H==1){
						textPane.append("Cost Function: "+(pathtotarget.getCostFunction()-1)+"\n");
						textPane.append("Heuristic: 0\n");
						textPane.append("Links To Source: "+pathtotarget.getSourceDistance()+"\n");
					}

					for (int i=0;i<pathtotarget.getStack().size();i++){					
						textPane.append(pathtotarget.getStack().get(i).getID()+"\n");					
					}
					textPane.append("***********************\n");
					textPane.append(temp+"\n");
					Transformer<Node, Paint> vertexColor = new Transformer<Node, Paint>() {
						@Override
						public Paint transform(Node arg0) {
							if (arg0 == source) {
								return Color.YELLOW;
							}
							else if (arg0 == target) {
								return Color.GREEN;
							}									
							else{										
								for (int i=0;i<finalstack.size();i++){
									Node node =finalstack.get(i);
									if (node.getID().equals(arg0.getID())){
										return Color.MAGENTA;
									}
								}
								return Color.WHITE;
							}

						}
					};
					viserver.getRenderContext().setVertexFillPaintTransformer(vertexColor);							
					Graph_pane.updateUI();

				}


				// Nodes Flag reset
				Iterator<Node> iter = nodes.iterator();
				while (iter.hasNext()){
					Node node = iter.next();
					node.setVisited(false);
				}
				threadPath=null;
				exe.setEnabled(true);
				loadGraph.setEnabled(true);
				chckPane.setEnabled(true);
				comboBox_heruristic.setEnabled(true);
				comboBox_start_city.setEnabled(true);
				comboBox_end_city.setEnabled(true);
				step.setEnabled(true);
				count =	chckPane.getComponentCount();
				for (int i=0; i<count;i++){
					JCheckBox ck = (JCheckBox) chckPane.getComponent(i);
					ck.setEnabled(true);
				}
			}
		};

		try {
			// Graph update based on astar
			if (viserver != null) {// is graph loaded in panel ?
				if(starnode.equals("none")||endnode.equals("none")){
					JOptionPane.showMessageDialog(null, "The Start or End city cannot be \"none\"");
				}else{
					if(threadPath==null){
						threadPath = new Thread(ro);
						threadPath.start();						
					}					
				}

			}
			else{
				JOptionPane.showMessageDialog(null, "Load Graph First");
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}



	}

	private void loadingpanel() {
		// Panel to load location and connection files.
		fl1 = new File("");
		fl2 = new File("");
		location = new JFrame();
		location.setVisible(true);
		location.setSize(300, 150);

		// Get the size of the screen
		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

		// Determine the new location of the window
		int w = location.getSize().width;
		int h = location.getSize().height;
		int x = (dim.width-w)/2;
		int y = (dim.height-h)/2;

		// Move the window
		location.setLocation(x, y);

		location.setResizable(false);
		pane = new JPanel();
		location.getContentPane().add(pane);

		// Determine the new location of the window

		connfile = new JTextField("Connection File", 20);
		connfile.setEditable(false);
		locfile = new JTextField("Location File", 20);
		locfile.setEditable(false);

		find1 = new JButton("Browse");
		find1.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				JFileChooser fc = new JFileChooser();
				FileNameExtensionFilter filter = new FileNameExtensionFilter(
						"txt files", "txt");
				fc.setFileFilter(filter);
				int returnVal = fc.showOpenDialog(location);
				if (returnVal == JFileChooser.APPROVE_OPTION) {
					fl1 = fc.getSelectedFile();
					if (fl1.getPath().contains("connsamp")) {
						connfile.setText(fl1.getAbsolutePath());
					} else {
						JOptionPane.showMessageDialog(null,
								"Please Select connsamp.txt");
					}
				}

			}
		});

		find2 = new JButton("Browse");
		find2.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				JFileChooser fc = new JFileChooser();
				FileNameExtensionFilter filter = new FileNameExtensionFilter(
						"Text Files", "txt");
				fc.setFileFilter(filter);
				int returnVal = fc.showOpenDialog(location);
				if (returnVal == JFileChooser.APPROVE_OPTION) {
					fl2 = fc.getSelectedFile();
					if (fl2.getPath().contains("locsamp")) {
						locfile.setText(fl2.getAbsolutePath());
					} else {
						JOptionPane.showMessageDialog(null,
								"Please Select locsamp.txt");
					}
				}

			}
		});
		nodes = new ArrayList<Node>();
		ok = new JButton("Ok");
		ok.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {

				if (fl1.exists() && fl2.exists()) {
					chckPane.removeAll();
					try {
						scanner = new Scanner(new FileInputStream(fl1));
					} catch (FileNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

					try {
						while (scanner.hasNextLine()) {
							line = scanner.nextLine();
							if (!line.equals("END")) {
								int index1 = line.indexOf(" ");
								String nodeID = line.substring(0, index1);

								int index2 = line.indexOf(" ", index1+1);
								String ncount = line.substring(index1+1, index2);

								String n = line.substring(index2+1);

								//Node Creation
								Node node = new Node();
								node.setID(nodeID);
								node.setNeighCount(Integer.parseInt(ncount));
								nodes.add(node);


								comboBox_start_city.addItem(nodeID);
								comboBox_end_city.addItem(nodeID);
								JCheckBox checkbox = new JCheckBox(nodeID);

								chckPane.add(checkbox);
							}

						}

					} finally {
						scanner.close();
					}



					// Add neighbors to each node
					try {
						scanner = new Scanner(new FileInputStream(fl1));
					} catch (FileNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

					try {
						while (scanner.hasNextLine()) {
							line = scanner.nextLine();
							if (!line.equals("END")) {
								int index1 = line.indexOf(" ");
								String nodeID = line.substring(0, index1);
								Node nodID = findNode(nodeID);

								int index2 = line.indexOf(" ", index1+1);
								String n = line.substring(index2+1);
								while (!n.equals("\n")){

									int ix1 = n.indexOf(" ");
									if (ix1==-1){
										String temp = n.substring(0);
										updateNeighbors(temp, nodID);
										break;
									}
									else{
										String temp = n.substring(0,ix1);
										updateNeighbors(temp, nodID);
										n = n.substring(ix1+1);
									}
								}
							}

						}
					} finally {
						scanner.close();
					}


					// Add position to each node
					try {
						scanner = new Scanner(new FileInputStream(fl2));
					} catch (FileNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

					try {
						while (scanner.hasNextLine()) {
							line = scanner.nextLine();
							if (!line.equals("END")) {
								int index1 = line.indexOf(" ");
								String nodeID = line.substring(0, index1);
								Node nodID = findNode(nodeID);

								String n = line.substring(index1+1);
								int ix1 = n.indexOf(" ");
								String x = n.substring(0,ix1);
								x = x.replaceAll("\\s", "");
								String y = n.substring(ix1+1);
								y = y.replaceAll("\\s", "");
								updatePosition(Integer.parseInt(x), Integer.parseInt(y), nodID);
							}

						}
					} finally {
						scanner.close();
					}


					location.dispose();
					mntmLoadConnectionAnd.setEnabled(false);
					exe.setEnabled(true);
					loadGraph.setEnabled(true);
				} else {
					JOptionPane.showMessageDialog(null,
							"Please load connection and location files");
				}

			}
		});

		cncl = new JButton("Cancel");
		cncl.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				location.dispose();

			}
		});

		GroupLayout layout = new GroupLayout(pane);
		pane.setLayout(layout);
		layout.setAutoCreateGaps(true);
		layout.setAutoCreateContainerGaps(true);
		layout.setHorizontalGroup(layout.createSequentialGroup()
				.addGroup(layout.createParallelGroup(Alignment.CENTER)
						.addComponent(locfile)
						.addComponent(connfile)
						.addGroup(layout.createSequentialGroup()
								.addComponent(ok)
								.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(cncl)))
								.addGroup(layout.createParallelGroup(Alignment.LEADING)
										.addComponent(find1).addComponent(find2)));
		layout.setVerticalGroup(layout.createSequentialGroup()
				.addGroup(layout.createParallelGroup(Alignment.BASELINE)
						.addComponent(connfile).addComponent(find1))
						.addGroup(layout.createParallelGroup(Alignment.BASELINE)
								.addComponent(locfile).addComponent(find2))
								.addGroup(layout.createParallelGroup(Alignment.CENTER)
										.addComponent(ok).addComponent(cncl)));

	}

	private void layoutPanel(){
		GroupLayout gl_heuristic_pane = new GroupLayout(heuristic_pane);
		heuristic_pane.setLayout(gl_heuristic_pane);
		gl_heuristic_pane.setAutoCreateGaps(true);
		gl_heuristic_pane.setAutoCreateContainerGaps(true);

		gl_heuristic_pane.setHorizontalGroup(
				gl_heuristic_pane.createSequentialGroup()
				.addGroup(gl_heuristic_pane.createParallelGroup(Alignment.CENTER)

						.addGroup(gl_heuristic_pane.createParallelGroup(Alignment.CENTER)
								.addComponent(lblHeuristic)
								.addComponent(comboBox_heruristic))

								.addGroup(gl_heuristic_pane.createSequentialGroup()
										.addGroup(gl_heuristic_pane.createParallelGroup(Alignment.CENTER)
												.addComponent(lblStartCity)
												.addComponent(comboBox_start_city)
												)
												.addGroup(gl_heuristic_pane.createParallelGroup(Alignment.CENTER)
														.addComponent(lblEndCity)
														.addComponent(comboBox_end_city))
										)
										.addGroup(gl_heuristic_pane.createSequentialGroup()												
												.addComponent(loadGraph)
												.addComponent(exe)
												.addComponent(step)
												)

						)
				);

		gl_heuristic_pane.setVerticalGroup(
				gl_heuristic_pane.createSequentialGroup()
				.addComponent(lblHeuristic)
				.addComponent(comboBox_heruristic,20,20,20)
				.addGroup(gl_heuristic_pane.createParallelGroup()
						.addComponent(lblStartCity)
						.addComponent(lblEndCity))

						.addGroup(gl_heuristic_pane.createParallelGroup()
								.addComponent(comboBox_start_city,20,20,20)						
								.addComponent(comboBox_end_city,20,20,20))
								.addGap(30)
								.addGroup(gl_heuristic_pane.createParallelGroup()
										.addComponent(loadGraph)
										.addComponent(exe)
										.addComponent(step)
										)				

				);

	}

	private Node findNode(String n){
		Iterator<Node> iterator = nodes.iterator();
		Node nod = null ;
		while (iterator.hasNext()){
			nod = iterator.next();
			if(nod.getID().equalsIgnoreCase(n)){
				break;
			}			
		}
		return nod;		
	}

	private void updateNeighbors(String f, Node n){
		Iterator<Node> iterator = nodes.iterator();
		Node nod;
		while (iterator.hasNext()){						
			nod = iterator.next();
			if (nod.getID().equals(f)){
				n.getNeighbors().add(nod);
				break;
			}

		}
	}

	private void updatePosition(int x, int y, Node n){
		Point pos = new Point(x, y);
		n.setPos(pos);
	}
}
